
package com.nuanshui.heatedloan.controller.display.users;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.nuanshui.heatedloan.userinfo.facade.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.nuanshui.heatedloan.service.services.CommonTool;
import com.nuanshui.heatedloan.enums.FileBelong;
import com.nuanshui.framework.cache.CacheConstants;
import com.nuanshui.framework.exception.BizException;
import com.nuanshui.framework.exception.GlobalErrorCode;
import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.framework.res.qiniu.Qiniu;
import com.nuanshui.framework.utils.redis.JedisUtil;
import com.nuanshui.heatedloan.constant.ActionCountType;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.controller.BaseController;
import com.nuanshui.heatedloan.controller.ResponseObject;
import com.nuanshui.heatedloan.userinfo.constant.IntegralActionType;
import com.nuanshui.heatedloan.userinfo.model.User;
import com.nuanshui.heatedloan.userinfo.model.UserInfo;
import com.nuanshui.heatedloan.userinfo.vo.IncrUserIntegralVo;
import com.nuanshui.heatedloan.userinfo.vo.SimplerUserInfoVO;
import com.nuanshui.heatedloan.userinfo.vo.UserIntegralVo;

@RestController
public class UserInfoController extends BaseController{

	private final static 	String QINIU_PRE_URL="qn|heatedloan|";

	@Reference(url=GlobalParam.USER_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
	private UserService userService;

	@Reference(url=GlobalParam.USER_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
	private UserQueryService userQueryService;

	@Reference(url=GlobalParam.USER_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
	private UserStateService userStateService;

	@Reference(url=GlobalParam.USER_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
	private UserAuthService userAuthService;
	
	@Reference(url=GlobalParam.USER_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
	private UserLogicService userLogicService;

	@Reference(url=GlobalParam.USER_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
	private UserFansRelationService userFansRelationService;

	@Reference(url=GlobalParam.USER_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
	private  UserIntegralService userIntegralService;
	
	@Reference(url=GlobalParam.USER_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
	private UserActionService userActionService;

	@Autowired
	private Qiniu qiniu;

	@Autowired
	private JedisUtil jedisUtil;

	@Autowired
	private CommonTool commonTool;

	/**
	 * 修改用户信息
	 * @param user
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/userinfo/modify",method = RequestMethod.POST)
	public String userInfoModify(UserInfo user,HttpServletRequest req){
		String name = user.getNick();
		if (!getCurrentUser().getId().equals(user.getId())){
			throw new BizException(GlobalErrorCode.UNAUTHORIZED, "用户未登录");
		}
		String avatar = user.getAvatar();
		if(avatar!= null && !avatar.startsWith(QINIU_PRE_URL)) {
			String bucketName = qiniu.genBucketName(FileBelong.PRODUCT);
			avatar = qiniu.qiniuKeyToLocalKey(avatar, bucketName);
			user.setAvatar(avatar);
		}
		String selfhoodImg  = user.getSelfhoodImg();
		if(StringUtils.isNotEmpty(selfhoodImg) && !selfhoodImg.startsWith(QINIU_PRE_URL)) {
			String bucketName = qiniu.genBucketName(FileBelong.PRODUCT);
			selfhoodImg = qiniu.qiniuKeyToLocalKey(selfhoodImg, bucketName);
			user.setSelfhoodImg(selfhoodImg);
		}
		User oldUser = userQueryService.load(user.getId());
		//修改头像和昵称的时候需要修成chat_token
		boolean isUpdateNick  = SysStringUtils.isNotEmpty(user.getNick())&& !user.getNick().equals(oldUser.getNick());
		boolean isUdpateSignature= SysStringUtils.isNotEmpty(user.getSignature()) &&!user.getSignature().equals(oldUser.getSignature());
		boolean isUpdateAvatar  = StringUtils.isNotEmpty(user.getAvatar()) && !user.getAvatar().equals(oldUser.getAvatar());
		if(isUpdateAvatar || isUpdateNick) {
			if(user.getNick() != null && StringUtils.isEmpty(user.getNick().trim())){
				user.setNick(oldUser.getNick());
			}
			if(StringUtils.isEmpty(user.getAvatar())) {
				user.setAvatar(oldUser.getAvatar());
			}
			//userTool.updateChatToken(user);
		}
		user.setLocation(commonTool.resolveLocation(user.getLongitude(),user.getLatitude(),req));
		userService.updateUserInfo(user,true);
		
		if(isUpdateNick) {
			
		}
		//加分
		List<String> actions = new ArrayList<String>();
		if(isUdpateSignature &&"寻宝之旅".equals(oldUser.getSignature())) actions.add(IntegralActionType.PERSONAL_DATA);
		if(isUpdateNick && "藏友".equals(oldUser.getNick())) actions.add(IntegralActionType.PERSONAL_DATA);
		if(oldUser.getAvatar() == null && user.getAvatar() !=null) actions.add(IntegralActionType.PERSONAL_DATA);
		//if(oldUser.getSex() == 2 && user.getSex() != 2) actions.add(IntegralActionType.PERSONAL_DATA);
		//if(oldUser.getAddress() == null && user.getAddress() != null)  actions.add(IntegralActionType.PERSONAL_DATA);
		//IncrUserIntegralVo incrUserIntegralVo =  userTool.incrUserIntegral(user.getId(),actions.toArray(new String[]{}));
		String userId = getCurrentUser().getId();
		//判断修改用户信息，删除缓存用户
		if(isUpdateAvatar || isUpdateNick || isUdpateSignature) {
			commonTool.deleteSimpleUserInfo(userId);
		}
		UserInfo userInfo = userLogicService.loadCurrentUserInfo(userId,true);
		//更新索引
		oldUser.setNick(user.getNick());
		oldUser.setSignature(user.getSignature());	
		return success(userInfo);
	}

	/**
	 * 关注/取消关注用户
	 * @param targetId 要关注的用户id
	 * @param checked  true 表示关注，false表示取消关注
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/interested/{targetId}/{checked}",method = RequestMethod.POST)
	public String interested(@PathVariable String targetId,String curUserId, @PathVariable boolean checked){
		if("(null)".equals(targetId)) return success(false);
		String currentUserId= curUserId;
		if(StringUtils.isEmpty(curUserId)) {//curUserId 为空 表示为app访问的，否则为web访问的
			currentUserId = getCurrentUser().getId();
		}
		if(currentUserId.equals(targetId)){
			throw new BizException(GlobalErrorCode.UNKNOWN, "亲，不能关注自己哦");
		}
		if(checked) {
			try {
				 userFansRelationService.insert(currentUserId, targetId);
				 commonTool.incrCount(ActionCountType.USER_FANS, targetId);
				 commonTool.incrCount(ActionCountType.USER_FOLLOWS, currentUserId);
			} catch (DuplicateKeyException e) {
				return success(true);
			}
		}else {
			userFansRelationService.delete(currentUserId, targetId);
			 commonTool.decrCount(ActionCountType.USER_FANS, targetId);
			 commonTool.decrCount(ActionCountType.USER_FOLLOWS, currentUserId);
		}	
		//发送消息
		/*if(checked){
			Set<String> set = new HashSet<String>();
			set.add(targetId);	
			msgTool.sendPushMsg(PushMessageType.INTERESTED, MsgOperationType.ADD, targetId, set);
			
		}else{
			Set<String> set = new HashSet<String>();
			set.add(targetId);			
			msgTool.sendPushMsg(PushMessageType.INTERESTED, MsgOperationType.DELETE, targetId,set);
		}*/
		return success(true);
	}

	@SuppressWarnings("resource")
	public static String postRequest(final String url,
			final Map<String, Object> rawParams) throws Exception {
		HttpClient httpClient = new DefaultHttpClient();
		// 创建HttpPost对象。
		HttpPost post = new HttpPost(url);
		// 设置请求参数
		post.setEntity(new ByteArrayEntity(JSON.toJSONString(rawParams).getBytes(),ContentType.APPLICATION_JSON));
		post.setHeader("Content-type", "application/json");
		// 发送POST请求
		HttpResponse httpResponse = httpClient.execute(post);
		// 如果服务器成功地返回响应
		if (httpResponse.getStatusLine().getStatusCode() == 200) {
			// 获取服务器响应字符串
			String result = EntityUtils.toString(httpResponse.getEntity());
			return result;
		}
		return null;
	}

	/**
	 * 用户详情
	 * @param userId
	 * @return
	 * @since 1.0.0
	 */
	@ResponseBody
	@RequestMapping(value = "/userInfo/{userId}",method = RequestMethod.POST)
	public String loadUserInfoById(@PathVariable String userId,HttpServletRequest req){
		jedisUtil.incr(CacheConstants.VIEW_USER_COUNT+userId);	
		UserInfo userItem=loadCurrentUserInfo(userId);
		/*if(isLoginUser()&&userItem!=null) {
			Integer time =  userIntegralService.getContinuousTime(IntegralActionType.SIGN,DateUtil.getToday("yyyy-MM-dd"));
			userItem.setIsSign(time!=null);
		}*/
		return success(userItem);		
	}
	
	@RequestMapping(value = "/userinfo/loadSimplerUserinfo",method = RequestMethod.POST)
	public String loadSimplerUserinfo(String userId) {	
	   /*SimplerUserInfoVO userItem=userLogicService.loadSimpleUserInfoVO(userId, userTool.getCurrentUserNotCheck().getId());
	    userItem.setIsSelf(userId.equals(userTool.getCurrentUserNotCheckEmptyId().getId()));
	   */
	   return success();	
	}
	
	@RequestMapping(value = "/userinfo/loadCurrentSimplerUserinfo",method = RequestMethod.POST)
	public String loadCurrentSimplerUserinfo(Integer needBuybackMsg) {	
	   String userId = getCurrentUser().getId();
	   SimplerUserInfoVO userItem=userLogicService.loadSimpleUserInfoVO(userId, "");
	    userItem.setIsSelf(true);
	    return success(userItem);	
	}

	/**
	 * 清空未读数
	 * @param 
	 * @author guohao
	 * @deprecated 1.1.0
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "userinfo/resetBadge",method = RequestMethod.POST)
	@ResponseBody
	@Deprecated
	public ResponseObject resetBadge(String userId) {
		if(userId == null || "(null)".equals(userId)) {
			return new ResponseObject("userId不能为空",GlobalErrorCode.INVALID_ARGUMENT);
		}
		userStateService.updateNotReadNum(userId, 0);
		return new ResponseObject();
	}
	
	/**
	 * 推荐用户
	 * @param userId
	 * @param checked
	 * @return
	 * @since 1.0.0
	 */
	@ResponseBody
	@RequestMapping(value = "/userinfo/recommend/{userId}/{checked}",method = RequestMethod.POST)
	public ResponseObject<Boolean> recommendUser(@PathVariable String userId ,@PathVariable boolean checked){
		User user = userQueryService.load(getCurrentUser().getId());
		if(!user.getAdmin().equals("-1")){
			throw new BizException(GlobalErrorCode.UNKNOWN, "没有权限");
		}
		User userinfo = new User();
		userinfo.setId(userId);
		userinfo.setRecommended(checked);
		return new ResponseObject<Boolean>(userService.updateUserInfo(userinfo,false));
	}

	/**
	 * 更新用户的某种权限
	 * @param type
	 * @param value
	 * @return
	 */
	@RequestMapping(value = "/userinfo/configUserAuth",method = RequestMethod.POST)
	public String configUserAuth(String type,Integer value) {
		userAuthService.updateUserAuth(type, value);
		return success();
	}
	
	/**
	 * 获取当前用户的所有权限
	 * @return
	 */
	@RequestMapping(value = "/userinfo/loadUserAuth",method = RequestMethod.POST)
	public String loadUserAuth() {		
		return success(userAuthService.loadUserAuth(getCurrentUser().getId()));
	}
	
	@RequestMapping("userinfo/addScore")
	public String addScore(String actionCode) {
		
	//	IncrUserIntegralVo incrUserIntegralVo =  userTool.incrUserIntegral(actionCode);
		return success();
		
	}

	/**
	 * 获取某个用户的所有权限
	 * @param sign
	 * @return
	 */
	@RequestMapping(value = "userinfo/loadUserScoreAndLevel",method = RequestMethod.POST)
	public String loadUserScoreAndLevel(Boolean sign) {	
		IncrUserIntegralVo incrUserIntegralVo = null;
		if(sign != null && sign) {//表示去签到
			   incrUserIntegralVo = userActionService.sign();		   
		}		
		HashMap<String, Object> map = userIntegralService.getParsedIntegralActionAndRank();	
		UserIntegralVo integralVo = userIntegralService.getUserIntegralVo();
		//积分等级兼容性问题
		/*if(!commonTool.allowExectue("200", "200")) {
			List<Double> doubles = (List<Double>) map.get("integralRanks");
			if(doubles!=null) {
				doubles.add(integralVo.getMaxScore());	
			}
		}*/	
		map.put("user", integralVo);
		if(sign!=null&&sign) {	
		    return success(map,incrUserIntegralVo);
		}
		return success(map);
	}

	/**
	 * 获取当前登录的用户
	 * @param userId
	 * @return
	 */
	private UserInfo loadCurrentUserInfo(String userId){
		return userLogicService.loadCurrentUserInfo(userId,false);
	}

	/**
	 * 设置关注状态
	 * @param 
	 * @author guohao
	 * @date 2015年6月15日 下午5:03:13
	 */
	private void setInterestedStatus(UserInfo userInfo) {
		userLogicService.setInterestedStatus(userInfo);
	}

}
